<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>记录表格实时选择的数据</title>
    <link rel="stylesheet" href="/assets/layui/css/layui.css">
    <script src="/assets/layui/layui.js"></script>
    <style>
      body {
        display: flex;
        justify-content: center;
      }
      #app {
        width: 1024px;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <table class="layui-hide" id="demo" lay-filter="demo"></table>
      <p id="result" style="color: red; font-size: 22px"></p>
    </div>
    <script>
      // 【基础数据】
      // 每页大小
      const pageSize = 3
      // 表格数据
      const tableData = [
        {
          merchandiseId: 1,
          putaway: true,
        },
        {
          merchandiseId: 2,
          putaway: false,
        },
        {
          merchandiseId: 3,
          putaway: true,
        },
        {
          merchandiseId: 4,
          putaway: false,
        },
        {
          merchandiseId: 5,
          putaway: true,
        },
      ]
      // 当前所有选中的数据
      const putaway = []

      layui.use(['table', 'jquery'], function () {
        var table = layui.table,
          $ = layui.jquery

        table.render({
          elem: '#demo',
          cellMinWidth: 200,
          page: {
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'], //自定义分页布局
            limits: [pageSize, 5, 10],
            limit: pageSize,
          },
          cols: [
            [
              { type: 'checkbox' },
              { field: 'merchandiseId', title: 'ID' },
              {
                field: 'putaway',
                title: '状态',
                templet: function (d) {
                  return d.putaway ? '已上架' : '未上架'
                },
              },
            ],
          ],
          data: tableData,
        })

        table.on('checkbox(demo)', function (obj) {
          const { type, checked } = obj

          const checkStatus = table.checkStatus('demo') // demo 即为基础参数 id 对应的值
          let pageCheckedArr = checkStatus.data // 获取当前选中行的数据

          // 勾选全选复选框
          if (type === 'all' && checked) {
            pageCheckedArr.forEach((item) => {
              const { merchandiseId: id, putaway: flag } = item
              const findIndex = putaway.findIndex((x) => x.id === id)
              if (findIndex === -1) {
                putaway.push({
                  id,
                  flag,
                })
              }
            })
          } else if (type === 'all' && !checked) {
            // 获取当前页
            const pageIndex = parseInt($('.layui-laypage-em').next().html())
            // 自行通过分页获取当前页码所有数据（取消全选时 checkStatus.data 无数据）
            pageCheckedArr = pagination(pageIndex, pageSize, tableData)

            // 取消勾选全选复选框
            pageCheckedArr.forEach((item) => {
              const { merchandiseId: id } = item
              const findIndex = putaway.findIndex((x) => x.id === id)
              if (findIndex !== -1) {
                putaway.splice(findIndex, 1)
              }
            })
          } else if (type === 'one' && checked) {
            // 勾选单行复选框
            const { merchandiseId: id, putaway: flag } = obj.data
            const findIndex = putaway.findIndex((x) => x.id === id)
            if (findIndex === -1) {
              putaway.push({
                id,
                flag,
              })
            }
          } else if (type === 'one' && !checked) {
            // 取消勾选单行复选框
            const { merchandiseId: id } = obj.data
            const findIndex = putaway.findIndex((x) => x.id === id)
            if (findIndex !== -1) {
              putaway.splice(findIndex, 1)
            }
          }

          console.log(
            '%cindex.html line:96 putaway',
            'color: #007acc;',
            putaway
          )
          $('#result').html(JSON.stringify(putaway))
          
          // console.log(obj.checked) //当前是否选中状态
          // console.log(obj.data) //选中行的相关数据
          // console.log(obj.type) //如果触发的是全选，则为：all，如果触发的是单选，则为：one
        })
      })

      // 分页函数
      function pagination(pageNo, pageSize, array) {
        var offset = (pageNo - 1) * pageSize
        return offset + pageSize >= array.length
          ? array.slice(offset, array.length)
          : array.slice(offset, offset + pageSize)
      }
    </script>
  </body>
</html>
